import 'package:flutter/material.dart';
import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:flutter_baselib/src/ui/load_state/load_empty_view.dart';
import 'package:flutter_baselib/src/ui/load_state/load_error_view.dart';
import 'package:flutter_baselib/src/ui/load_state/load_state_parent_view.dart';
import 'package:flutter_baselib/src/ui/load_state/loading_view.dart';

///@date:  2021/3/1 13:38
///@author:  lixu
///@description:View 基类,配合[BaseViewModel]使用
///封装http通用加载错误页，空白页以及正常显示页UI和逻辑，UI可自定义
class BaseView<T extends BaseCommonViewModel> extends StatelessWidget {
  ///加载成功后显示的页面
  final Widget child;

  ///加载中页面
  final Widget? loadingChild;

  ///数据为空的页面
  final Widget? emptyChild;

  ///请求失败显示的页面
  final Widget? errorChild;

  BaseView({required this.child, this.loadingChild, this.emptyChild, this.errorChild});

  @override
  Widget build(BuildContext context) {
    LogUtils.i('BaseView', 'build:${child.toString()}');

    return Consumer<T>(
      child: child,
      builder: (BuildContext context, T viewModel, Widget? child) {
        if (viewModel.isSuccess()) {
          return child!;
        } else {
          return FutureBuilder(
            future: viewModel.onLoading(context),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (viewModel.isFail()) {
                  ///加载失败
                  return _getErrorWidget(viewModel);
                } else if (viewModel.isEmpty()) {
                  ///数据为空
                  return _getEmptyWidget(viewModel);
                } else {
                  ///加载成功
                  return child!;
                }
              } else {
                ///加载中
                return _getLoadingWidget();
              }
            },
          );
        }
      },
    );
  }

  Widget _getErrorWidget(T viewModel) {
    return LoadStateParentView(
      (errorChild != null ? errorChild : BaseLibPlugin.resConfig.configLoadErrorView() ?? LoadErrorView())!,
      _onRefresh(viewModel),
    );
  }

  Widget _getEmptyWidget(T viewModel) {
    return LoadStateParentView(
      (emptyChild != null ? emptyChild : BaseLibPlugin.resConfig.configLoadEmptyView() ?? LoadEmptyView())!,
      _onRefresh(viewModel),
    );
  }

  Widget _getLoadingWidget() {
    return LoadStateParentView(
      (loadingChild != null ? loadingChild : BaseLibPlugin.resConfig.configLoadingView() ?? LoadingView())!,
      null,
    );
  }

  ///刷新页面
  VoidCallback _onRefresh(T viewModel) {
    return () {
      viewModel.notifyListeners();
    };
  }
}
